package com.yanqu.road.player;

import com.yanqu.road.AgentServer;
import com.yanqu.road.connect.AgentServerConnection;
import com.yanqu.road.AgentServerNettyService;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.queue.ICommandQueue;
import com.yanqu.road.queue.AutoDriveQueue;

import io.netty.channel.Channel;

public class Player implements ICommandQueue {

    private final long playerId;
    private AgentServerConnection agentServerConnection;

    private final AutoDriveQueue<Runnable> commandQueue = new AutoDriveQueue<Runnable>(AgentServer.getServerCommandExecutor());

    public AutoDriveQueue<Runnable> getCommandQueue() {
        return commandQueue;
    }

    public void closeChannel() {
        if (agentServerConnection != null) {
            agentServerConnection.close();
        }
    }

    public AgentServerConnection getAgentServerConnection() {
        return agentServerConnection;
    }

    public Channel getChannel() {
        if (agentServerConnection != null) {
            return agentServerConnection.getChannel();
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(playerId).append("::").append(agentServerConnection.hashCode());
        return sb.toString();
    }


    public Player(final long playerId, Channel channel) {
        this.playerId = playerId;
        channel.attr(AgentServerNettyService.KEY_FOR_PLAYER_ID).set(playerId);
        agentServerConnection = new AgentServerConnection(channel);
    }

    public Player(final long playerId) {
        this.playerId = playerId;
    }

    public void setChannel(Channel channel) {
        channel.attr(AgentServerNettyService.KEY_FOR_PLAYER_ID).set(playerId);
        agentServerConnection = new AgentServerConnection(channel);
    }

    public long getPlayerId() {
        return playerId;
    }

    public void send(YanQuMessage message) {
        if (null != agentServerConnection) {
            agentServerConnection.write(message);
        }
    }


}
